//index.js
//获取应用实例
const app = getApp()
const url = app.basicsUrl();
Page({
  data: {
    diffcult: [
      {
        "title": "简单",
        "is_checked": false,
        "idx": 'easy'
      },
      {
        "title": "正常",
        "is_checked": true,
        "idx": 'common'
      },
      {
        "title": "困难",
        "is_checked": false,
        "idx": 'hard'
      },
      {
        "title": "变态",
        "is_checked": false,
        "idx": 'superHard'
      }
    ],
    moneys: [
      {
        "money": "10",
        "idx": "1",
        "is_checked": false
      },
      {
        "money": "30",
        "idx": "1",
        "is_checked": true
      },
      {
        "money": "100",
        "idx": "1",
        "is_checked": false
      },
      {
        "money": "200",
        "idx": "1",
        "is_checked": false
      },
      {
        "money": "...",
        "idx": "1",
        "is_checked": false
      }
    ],
    gameIndex: 0,
    gameList: [],
    gameData: [],
    service_money: "0.00",//服务费用
    payMoney: "30",//支付金额
    hongBaoNum: "",//奖励数量
    info: "",//奖励描述
    other_is_show: false,
    overflow_y: "",
    hongBaoType: '2',//1：普通奖励 2 拼手气奖励
    gameId: "1",
    totalPayMoney: "0.00",
    introduce: true,
    switchIsShow:false
  },
  onLoad: function () {

  },
  onShow: function () {
    var that = this;
    that.wxLogin();
    that.questionTypes();
  },//设置难度
  setDiffcut(e) {
    var that = this;
    var idx = e.target.dataset.index;
    var data = that.data.diffcult;
    for (var i = 0; i < data.length; i++) {
      data[i].is_checked = false;
    }
    data[idx].is_checked = true;
    that.setData({ diffcult: data })
  },//切换奖励游戏类型
  switchRedType() {
    var that = this;
    var hongBaoType = that.data.hongBaoType;
    var redType = hongBaoType == 1 ? 2 : 1;
    that.setData({
      hongBaoType: redType
    })
  },//选择游戏
  bindPickerChange(e) {
    var that = this;
    var index = e.detail.value
    var data = that.data.gameData;
    var gameId = data[index]['id'];//游戏id
    that.setData({
      gameIndex: index,
      gameId: gameId
    })
  },//选择奖励金额
  select_money(e) {
    var that = this;
    var money = e.target.dataset.money;
    var idx = e.target.dataset.index;
    var data = that.data.moneys;
    var len = data.length;
    for (var i = 0; i < len; i++) {
      data[i].idx = 1;
    }
    data[idx].idx = 2;
    that.setData({
      moneys: data
    })
    if (money < 1000) {
      var service_money = (money * 0.02).toFixed(2);
      var payMoney = Number(money).toFixed(2);
      var totalPayMoney = (Number(service_money) + Number(payMoney)).toFixed(2);
      that.setData({
        service_money: service_money,
        payMoney: payMoney,
        overflow_y: "",
        totalPayMoney: totalPayMoney
      })
    } else {
      that.setData({
        other_is_show: true,
        overflow_y: "hidden"
      })
    }
  },//奖励个数
  numInput(e) {
    var hongBaoNum = e.detail.value;
    this.setData({
      hongBaoNum: hongBaoNum
    })
  },//奖励描述
  discriptionInput(e) {
    var info = e.detail.value;
    this.setData({
      info: info
    })
  },//玩法介绍
  play_introduce() {
    var that = this;
    var introduce = that.data.introduce;
    this.setData({
      introduce: !introduce
    })
  },
  clickPopBg() {
    this.setData({
      other_is_show: false, 
      service_money: "0.00",
      overflow_y: ""
    })
  },//输入更多金额
  payMoneyInput(e) {
    var that = this;
    var idx = e.detail.value;
    var service_money = (idx * 0.02).toFixed(2);
    var payMoney = Number(idx).toFixed(2);
    var totalPayMoney = (Number(service_money) + Number(payMoney)).toFixed(2);

    that.setData({
      service_money: service_money,
      payMoney: payMoney,
      overflow_y: "",
      totalPayMoney: totalPayMoney
    })
  },//确认输入更多金额
  submitMoney() {
    var that = this;
    this.setData({
      other_is_show: false
    })
    // that.judgePayment();
  },
  wxLogin() {
    var that = this;
    wx.login({
      success: res => {
        var code = res.code;
        // 获取用户信息
        wx.getSetting({
          success: res => {
            // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
            wx.getUserInfo({
              success: res => {
                res.userInfo['code'] = code;
                var userInfo = res.userInfo;
                that.login(userInfo);
              }
            })
          }
        })
      }
    })
  },
  login(userInfo) {
    var that = this;
    var params = {};
    params['jsCode'] = userInfo.code;
    params['nickname'] = userInfo.nickName;
    params['sex'] = userInfo.gender;
    params['city'] = userInfo.city;
    params['province'] = userInfo.province;
    params['headimgurl'] = userInfo.avatarUrl;
    wx.request({
      url: url + 'login',
      data: params,
      success: res => {
        var loginInfo = res.data.data;
        var nikeName = userInfo.nickName
        loginInfo['nikeName'] = nikeName;
        that.setData({ loginInfo: loginInfo })
        wx.setStorage({
          key: "loginInfo",
          data: loginInfo
        })
      }
    })
  },//创建奖励
  createOrder() {
    var that = this;
    wx.showLoading({
      title: '加载中',
      mask:true
    })

    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userInfo']) {
          wx.openSetting({
            success: (res) => {
              if (res['authSetting']['scope.userInfo']) {
                // that.wxLogin();
              }
            }
          })
        }
      }
    })
    var loginInfo = that.data.loginInfo;
    if (!loginInfo) {
      return;
    }
    var params = {};
    params['gameId'] = 1;//游戏Id
    var diffcult = this.data.diffcult;
    for (var i = 0; i < diffcult.length; i++) {
      if (diffcult[i]['is_checked']) {
        params['hardType'] = diffcult[i]['idx'];//难易度
      }
    }
    params['hongBaoType'] = that.data.hongBaoType;//奖励类型1：平均奖励，2随机奖励
    var payMoney = that.data.payMoney* 100;
    if (payMoney < 1) {
      wx.showToast({
        title: '请选择奖励金额',
        icon: 'loading'
      })
      return;
    }
    params['payMoney'] = payMoney;//支付金额
    var hongBaoMoney = that.data.payMoney * 100;
    params['hongBaoMoney'] = hongBaoMoney;//奖励金额
    var hongBaoNum = that.data.hongBaoNum;
    if (hongBaoNum < 1) {
      wx.showToast({
        title: '请输入红包个数',
        icon: 'loading'
      })
      return;
    }
    params['hongBaoNum'] = hongBaoNum;//奖励数量
    var info = that.data.info;
    if (!info){
      info ="限时完成答题游戏就可获得奖励！";
    }
    params['info'] = info;//奖励描述信息
    params['tokenKey'] = loginInfo.id;
    params['openId'] = loginInfo.openId;
    params['token'] = loginInfo.token;
    params['questionType'] = that.data.gameId;
    wx.request({
      url: url + "authorized/createOrder",
      data: params,
      header: {
        'content-type': 'appliction/json'
      },
      success: res => {
        if (res.data.code == 200) {
          var hongBao = res.data.data.hongBao
          var payInfo = res.data.data.payInfo;
          if (payInfo) {
            var timeStamp = payInfo.timeStamp;//时间戳从1970年1月1日00:00:00至今的秒数,即当前的时间
            var nonceStr = payInfo.nonceStr;//随机字符串，长度为32个字符以下
            var packages = payInfo.package;
            var paySign = payInfo.paySign;
            wx.requestPayment({
              timeStamp: timeStamp,
              nonceStr: nonceStr,
              package: packages,
              signType: 'MD5',
              paySign: paySign,
              success: res => {
                if (res.errMsg == 'requestPayment:ok') {
                  if (hongBao.state == "create") {
                    var hongBaoHardType = hongBao.hongBaoHardType;
                    var gameId = hongBao.gameId;
                    var hongbaoId = hongBao.id;
                    wx.redirectTo({
                      url: '../../pages/forward/forward?gameId=' + gameId + "&hongBaoHardType=" + hongBaoHardType + "&hongbaoId=" + hongbaoId,
                    })
                  }
                }
              },
              fail: res => {
                wx.showModal({
                  title: '提示',
                  content: res.errMsg,
                })
              }
            })
          } else {
            if (hongBao.state == "payed") {
              var hongBaoHardType = hongBao.hongBaoHardType;
              var gameId = hongBao.gameId;
              var hongbaoId = hongBao.id;
              wx.redirectTo({
                url: '../../pages/forward/forward?gameId=' + gameId + "&hongBaoHardType=" + hongBaoHardType + "&hongbaoId=" + hongbaoId,
              })
            }
          }
          setTimeout(function () {
            wx.hideLoading()
          }, 2000)
        } else {
          wx.showToast({
            title: res.data.msg,
          })
        }

      }
    })
  },//问题类型
  questionTypes() {
    wx.request({
      url: url + 'questionTypes',
      data: {},
      success: res => {
        var data = res.data.data;
        if (res.data.code == 200) {
          var data = res.data.data,
            len = data.length,
            arr = new Array();
          for (var i = 0; i < len; i++) {
            arr.push(data[i]['name'])
          }
          this.setData({
            gameList: arr,
            gameData: data
          })
        } else {
          wx.showToast({
            title: res.data.msg,
          })
        }
      }
    })
  },
  judgePayment() {
    var that = this;
    wx.getStorage({
      key: 'loginInfo',
      success: function (res) {
        var data = res.data;
        var params = {};
        params['tokenKey'] = data.id;
        params['openId'] = data.openId;
        params['token'] = data.token;
        params['pay'] = Math.ceil(Number(that.data.payMoney) * 100);
        wx.request({
          url: url + "authorized/payFromBalance",
          data: params,
          header: {
            'content-type': 'application/json'
          },
          success: res => {
            if (res.data.code == 200) {
              if (!res.data.data) {

              }
            } else {
              wx.showLoading({
                title: res.data.msg,
              })
              setTimeout(function () {
                wx.hideLoading()
              }, 2000)
            }
          },
          fail: res => {
            wx.showLoading({
              title: res.data.msg,
            })
            setTimeout(function () {
              wx.hideLoading()
            }, 2000)
          }
        })
      },
      fail: res => {
        wx.showLoading({
          title: '获取参数失败',
        })
        setTimeout(function () {
          wx.hideLoading()
        }, 2000)
      }
    })
  },//新版选择金额
  chooseMoney(e){
    var that=this;
    var idx=e.currentTarget.dataset.index;
    var switchIsShow;
    if(idx==4){
      switchIsShow=true;
    }
    var data=that.data.moneys;
    var len = data.length;
    for (var i = 0; i < len; i++) {
      data[i].is_checked = false;
    }
    data[idx].is_checked = true;
    that.setData({
      moneys: data,
      switchIsShow: switchIsShow,
      payMoney: data[idx]['money']
    })
  },
  inputMoney(e){
    var that=this;
    var val = e.detail.value;
    that.setData({
      payMoney: val
    })
  }
})
